package itsen.com.bduidemo.modle.event.demo;

import android.content.Context;
import android.graphics.Point;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.ViewDragHelper;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import itsen.com.bduidemo.R;
import itsen.com.bduidemo.lib.tool.LogTool;

/**
 * Created by 周德森
 * Created time 2017/10/25 21:44
 * Description:DNui
 * Version: V 1.0
 */

public class BehaviorLayoutList extends CoordinatorLayout.Behavior<LinearLayout> {
    private VelocityTracker mVelocityTracker;
    private ViewDragHelper mViewDragHelper;
    private ViewDragHelper.Callback callback;
    private MyRecycleView mRecyclerView;
    private TextView mTvCk;
    private ViewGroup lyContext;
    private Point pointHeight;
    private int parentHeight;//父布局高度
    private int topHeight;//头部栏高度
    private int tvCkHeight;//查看栏高度
    private final int STATE_TOP = 1;//状态1
    private final int STATE_CENTER = 2;//状态2
    private final int STATE_BOTTON = 3;//状态3
    private final int SLPOB = 5;//状态3
    private boolean isLockCenter = false;
    private boolean isFocusOnbtn;
    private float lastY;//手指按下的距离
    private int mCurrentState = STATE_TOP;//当前状态
    private String mTvText[] = {"", "隐藏", "", "查看"};

    public BehaviorLayoutList(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onLayoutChild(CoordinatorLayout parent, LinearLayout child, int layoutDirection) {
        parentHeight = parent.getHeight();
        lyContext = (ViewGroup) parent.getChildAt(1);
        mRecyclerView = (MyRecycleView) lyContext.getChildAt(3);
        mTvCk = (TextView) lyContext.getChildAt(1);
        mTvCk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogTool.e("onClick");
                if (mCurrentState == STATE_TOP) {
                    mCurrentState = STATE_BOTTON;
                } else {
                    mCurrentState = STATE_TOP;
                }
                mTvCk.setText(mTvText[mCurrentState]);
                /**
                 * 方式一：lyContext.setY(getPoint(mCurrentState).y);  生硬，没有过度效果
                 * 方式二：
                 * 方式三：属性动画
                 */
                if (mViewDragHelper.smoothSlideViewTo(lyContext, getPoint(mCurrentState).x, getPoint(mCurrentState).y)) {
                    ViewCompat.postOnAnimation(lyContext, new SettleRunnable(lyContext));
                }
            }
        });
        mTvCk.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        isFocusOnbtn = true;
                        LogTool.e("btn down");
                        break;
                    case MotionEvent.ACTION_UP:
                        LogTool.e("btn up");
                        isFocusOnbtn = false;
                        break;
                    default:
                        break;
                }

                return false;
            }
        });
        return super.onLayoutChild(parent, child, layoutDirection);
    }

    @Override
    public boolean layoutDependsOn(CoordinatorLayout parent, LinearLayout child, View dependency) {
        return super.layoutDependsOn(parent, child, dependency);
    }

    @Override
    public boolean onDependentViewChanged(CoordinatorLayout parent, LinearLayout child, View dependency) {
        return super.onDependentViewChanged(parent, child, dependency);
    }

    @Override
    public boolean onInterceptTouchEvent(CoordinatorLayout parent, LinearLayout child, MotionEvent ev) {

        int action = MotionEventCompat.getActionMasked(ev);
        if (mViewDragHelper == null) {
            initViewDragCallBack();
            mViewDragHelper = ViewDragHelper.create(parent, callback);
        }
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                lastY = ev.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                //LogTool.e("ACTION_MOVE y:" + ev.getY());
                //焦点在btn上，并且recycleView处于顶部状态，这不拦截事件。
                if (!isFocusOnbtn && mRecyclerView.canScrollVertically(-1)) {
                    return false;
                }
                break;
            case MotionEvent.ACTION_UP:
                break;
            default:
                break;
        }

        return mViewDragHelper.shouldInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(CoordinatorLayout parent, LinearLayout child, MotionEvent ev) {
        int action = ev.getAction();
        mViewDragHelper.processTouchEvent(ev);
        return true;
    }

    /**
     * 初始化拖拽回调
     */
    private void initViewDragCallBack() {
        callback = new ViewDragHelper.Callback() {
            @Override
            public boolean tryCaptureView(View child, int pointerId) {
                return child.getId() == R.id.ly_context;
            }

            @Override
            public int clampViewPositionVertical(View child, int top, int dy) {
                setmCurrentState(top);
                // LogTool.e("top:" + top);
                if (top <= 0) {
                    return 0;
                } else if ((top + topHeight) >= (parentHeight - tvCkHeight)) {
                    return parentHeight - (tvCkHeight + topHeight);
                }
                return top;
            }

            @Override
            public void onViewReleased(final View releasedChild, float xvel, float yvel) {
                isLockCenter = false;
                isFocusOnbtn = false;
                mTvCk.setText(mTvText[mCurrentState]);
                mViewDragHelper.settleCapturedViewAt(getPoint(mCurrentState).x, getPoint(mCurrentState).y);
                ViewCompat.postOnAnimation(releasedChild,
                        new Runnable() {
                            @Override
                            public void run() {
                                if (mViewDragHelper != null && mViewDragHelper.continueSettling(true)) {
                                    ViewCompat.postOnAnimation(releasedChild, this);
                                }
                            }
                        });
            }

            @Override
            public int getViewVerticalDragRange(View child) {
                return SLPOB;
            }
        };
    }

    /**
     * 外部获取实例
     *
     * @param view
     * @return
     */
    public static BehaviorLayoutList from(android.widget.LinearLayout view) {
        ViewGroup.LayoutParams params = view.getLayoutParams();
        if (!(params instanceof CoordinatorLayout.LayoutParams)) {
            throw new IllegalArgumentException("The view is not a child of CoordinatorLayout");
        }
        CoordinatorLayout.Behavior behavior = ((CoordinatorLayout.LayoutParams) params)
                .getBehavior();
        if (!(behavior instanceof BehaviorLayoutList)) {
            throw new IllegalArgumentException(
                    "The view is not associated with MyBehavior");
        }
        return (BehaviorLayoutList) behavior;
    }


    private Point getPoint(int type) {
        if (pointHeight == null) {
            pointHeight = new Point();
            pointHeight.x = 0;
        }
        switch (type) {
            case STATE_TOP:
                pointHeight.y = 0;
                break;
            case STATE_CENTER:
                pointHeight.y = parentHeight / 2;
                break;
            case STATE_BOTTON:
                pointHeight.y = parentHeight - (topHeight + tvCkHeight);
                break;
        }
        return pointHeight;
    }

    /**
     * 头部栏高度
     *
     * @param topHeight
     */
    public void setTopHeight(int topHeight) {
        this.topHeight = topHeight;
    }

    /**
     * 查看栏高度
     *
     * @param tvCkHeight
     */
    public void setTvCkHeight(int tvCkHeight) {
        this.tvCkHeight = tvCkHeight;
    }

    /**
     * 设置即将要移动的位置状态
     *
     * @param top
     */
    public void setmCurrentState(int top) {
        int middleHeight = parentHeight / 2;
        int threeHeight = middleHeight / 3;
        if (top > threeHeight && top < middleHeight + threeHeight * 2) {
            //在中间移动过程中解决转台相互转换的问题，所以加锁判断
            if (!isLockCenter) {
                isLockCenter = true;
            } else {
                return;
            }
            if (mCurrentState == STATE_TOP) {
                mCurrentState = STATE_BOTTON;
            } else {
                mCurrentState = STATE_TOP;
            }
            LogTool.e("mCurrentState:" + mCurrentState);
            return;
        }
        if (top <= threeHeight) {
            mCurrentState = STATE_TOP;
            isLockCenter = false;
            return;
        }

        if (top >= (middleHeight + threeHeight * 2)) {
            isLockCenter = false;
            mCurrentState = STATE_BOTTON;
        }
    }

    /**
     * 线程 执行相关view的动画
     */
    private class SettleRunnable implements Runnable {
        private final View mView;

        SettleRunnable(View mView) {
            this.mView = mView;
        }

        @Override
        public void run() {
            if (mViewDragHelper != null && mViewDragHelper.continueSettling(true)) {
                ViewCompat.postOnAnimation(mView, this);
            }
        }
    }
}
